#-*- encoding: UTF-8 -*-

from jinja2 import Environment, PackageLoader
import config
import datetime
import hashlib
import json
import math
import model
import random
import web

'''
Created on 2012-10-09

@author: wicki
'''

web.config.debug = False

#url mappings
urls = (
    '/createlogin','CreateLogin',
    '/register','Register',
)

app = web.application(urls, globals())
env = Environment(loader=PackageLoader('DLSite','templates'))

def write_json(obj):
    web.header('Content-Type', 'application/json')
    return json.dumps(obj)

def generate_key():
    key = ""
    for i in range(0, 32):
        index = math.floor(random.random()*len(config.RANDOM_SEED))
        k = config.RANDOM_SEED[index,index+1]
        key += k
    return key


class CreateLogin:
    def GET(self):
        data = web.input()
        username = data.username
        key = data.key
        localkey = hashlib.sha1(username+config.LOGIN_KEY).hexdigest()
        if key == localkey:
            keys = model.db.select('loginkey',where='username=$username',vars=locals())
            key = generate_key()
            if len(keys) > 0:
                model.db.update('loginkey',key=key,where='username=$username',vars=locals())
            else:
                model.db.insert('loginkey',username=username,key=key,posted=datetime.datetime.utcnow())
                return write_json({'result':True,'key':key})
        return write_json({'result':False})
    
class Register:
    def POST(self):
        data = web.input()
        username = data.username
        nickname = data.nickname
        gender = data.gender
        key = data.key
        v = {"username":username,"key":key}
        keys = model.db.query('select * from user where username=$username and password=$password', v)
        if len(keys) > 0:
            key = keys[0]
            now = datetime.datetime.utcnow()
            t = key.posted - now
            if t.days==0 and t.seconds<=5*60:
                users_u = model.db.select('user',where='username=$username',vars=locals())
                if len(users_u)>0:
                    return write_json({'result':False,'message':'用户名已存在'})
                elif len(model.db.select('user',where='nickname=$nickname',vars=locals()))>0:
                    return write_json({'result':False,'message':'昵称已存在'})
                else:
                    model.db.insert('user',UserName=username,NickName=nickname,gender=gender,Level=config.Level,Exp=config.Exp,Avatar=config.Avatar,TotalMp=config.TotalMp,TotalHp=config.TotalHp,Actions=config.Actions,Attack=config.Attack,Defence=config.Defence,Strength=config.Strength,Agility=config.Agility,Intelligence=config.Intelligence,Hit=config.Hit,Dodge=config.Dodge,Crit=config.Crit,WalkSpeed=config.WalkSpeed,Money=config.Money)
                    return write_json({'result':True})
        return write_json({'result':False,'message':'您尚未登录或登录已超时'})
                    
if __name__ == '__main__': #for local
    app.run()

#application = app.wsgifunc() #for linode 
